package handler

import (
	"github.com/gin-gonic/gin"
	"NicePay/websocket"
	"gopkg.in/olahol/melody.v1"
	"encoding/json"
)

var WsHandler = gin.HandlerFunc(func(ctx *gin.Context) {
	mel := websocket.Obtain()
	mel.HandleConnect(func(s *melody.Session) {
		s.Set("uid", ctx.Value("uid"))
	})
	mel.HandleMessage(func(s *melody.Session, msg []byte) {
		m := new(websocket.Msg)
		json.Unmarshal(msg, m)
		switch m.Tag {
		case "GetQr":
			if uid, ok := s.Get("uid"); ok {
				m.GetQr(uid.(uint))
			} else {
				return
			}
		default:
			return
		}
		resBytes, _ := json.Marshal(m)
		s.Write(resBytes)
	})
	mel.HandleDisconnect(func(s *melody.Session) {
		s.CloseWithMsg([]byte("closed successful"))
	})
	mel.HandleRequest(ctx.Writer, ctx.Request)
})
